<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="data" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="采购订单名称" prop="po_Name">
                    <el-input v-model="data.po_Name" placeholder="采购订单名称" />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="销售单号" style="margin-bottom: 30px;">
                            <el-input v-model="data.po_Code" placeholder="自动获取编号" disabled/>
                        </el-form-item>
                        <el-form-item label="联系人" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_Name" placeholder="联系人" disabled />
                        </el-form-item>
                        <!-- <el-form-item label="订单签订日期" prop="po_Starttime" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.po_Starttime" type="date" width="460"
                                placeholder="请选择签订日期" :size="size" style="width: 460px;" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"/>
                        </el-form-item> -->
                        <el-form-item label="订单签订日期" prop="po_Starttime" style="margin-bottom: 30px;"
                            :rules="[
                            { required: true, message: '请选择签订日期', trigger: 'change' },
                            { type: 'date', message: '请输入有效的日期', trigger: 'change' }
                        ]">
                            <el-date-picker 
                                v-model="data.po_Starttime" 
                                type="date" 
                                placeholder="请选择签订日期" 
                                :size="size" 
                                style="width: 460px;" 
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"  
                                format="YYYY-MM-DD"  
                                :editable="false"  
                                :clearable="true"  
                            />
                            </el-form-item>
                        <!-- <el-form-item label="负责人部门" prop="vendor_depd_id" style="margin-bottom: 30px;">
                        <el-tree-select v-model="data.vendor_depd_id" :data="deptOptions" :props="defaultProps"
                                :check-strictly="true" placeholder="请选择采购部门" @change="getUser()" >
                                <template #header>
                                    <el-input v-model="deptName" placeholder="请搜索采购部门" style="padding: 5px"
                                    @input="getDeptDebounced" />
                                </template>
                                </el-tree-select>
                        </el-form-item> -->

                        <el-form-item label="负责人部门" prop="vendor_depd_id" style="margin-bottom: 30px;" :rules="[
                            { required: true, message: '请选择采购部门', trigger: 'change' }
                        ]">
                            <el-tree-select v-model="data.vendor_depd_id" :data="deptOptions" :props="defaultProps"
                                    :check-strictly="true" placeholder="请选择采购部门" @change="getUser()" >
                                    <!-- <template #header>
                                        <el-input size="small" v-model="deptName" placeholder="请搜索采购部门" style="padding: 5px"
                                        @input="getDeptDebounced" />
                                    </template> -->
                                    </el-tree-select>
                        </el-form-item>
                        <!-- <el-form-item label="采购负责人" style="margin-bottom: 30px;">
                            <el-select v-model="data.po_Rep_Id" placeholder="请选择采购负责人">
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="采购负责人" prop="po_Rep_Id" style="margin-bottom: 30px;" :rules="[
                            { required: true, message: '请选择采购负责人', trigger: 'change' }
                        ]">
                            <el-select v-model="data.po_Rep_Id" placeholder="请选择采购负责人">
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <!-- <el-form-item label="供应商昵称" prop="po_Endor_Code" style="margin-bottom: 30px;">
                            <el-select v-model="data.po_Endor_Code" placeholder="请选择供应商" @change="customerEndit">
                                <template #header>
                                    <el-input v-model="vendor_name" placeholder="搜索客户" style="padding: 5px"
                                        @input="getCustomerDebounced" />
                                </template>
                                <el-option v-for="item in customerOptons" :key="item.vendor_code"
                                    :label="item.vendor_name" :value="item.vendor_code" />
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="供应商昵称" prop="po_Endor_Code" style="margin-bottom: 30px;" :rules="[
                            { required: true, message: '请选择供应商', trigger: 'change' }
                        ]">
                            <el-select v-model="data.po_Endor_Code" placeholder="请选择供应商" @change="customerEndit">
                                <!-- <template #header>
                                    <el-input size="small" v-model="vendor_name" placeholder="搜索供应商" style="padding: 5px"
                                        @input="getCustomerDebounced" />
                                </template> -->
                                <el-option v-for="item in customerOptons" :key="item.vendor_code"
                                    :label="item.vendor_name" :value="item.vendor_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联系方式" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_Phone" placeholder="联系方式" disabled />
                        </el-form-item>
                        <!-- <el-form-item prop="po_Endtime" label="订单交付日期" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.po_Endtime" type="date"
                                placeholder="请选择交付日期" :size="size" style="width: 460px;" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"/>
                        </el-form-item> -->
                        <el-form-item 
                            prop="po_Endtime" 
                            label="订单交付日期" 
                            style="margin-bottom: 30px;"
                            :rules="[
                                { required: true, message: '请选择交付日期', trigger: 'change' },
                                { type: 'date', message: '请输入有效的日期', trigger: 'change' }
                            ]"
                            >
                            <el-date-picker 
                                v-model="data.po_Endtime" 
                                type="date" 
                                placeholder="请选择交付日期" 
                                :size="size" 
                                style="width: 460px;" 
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                                format="YYYY-MM-DD" 
                                :editable="false" 
                                :clearable="true"
                            />
                            </el-form-item>
                        <el-form-item prop="warehouse_Code" label="入库仓库编号" style="margin-bottom: 30px;">
                            <el-select v-model="data.warehouse_Code" placeholder="请选择仓库">
                                <el-option v-for="item in CKOptions" :key="item.warehouse_code" :label="item.warehouse_name"
                                    :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="备注" prop="Remark">
                    <el-input v-model="data.Remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">采购产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="货品名称" />
                <el-table-column prop="pro_code" label="货品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="dict_code" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="采购数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.po_number" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="采购单价">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_cost_price" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="成本合计">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_cost }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">采购总数量：{{ sale_total_qty }} &nbsp;&nbsp;&nbsp; 采购成本总额：{{
                        Number(cost_total_proce).toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input size="small" v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <!-- <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select> -->
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReaslt">重置</el-button>
                <el-button type="primary" @click="productEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="pro_name" label="货品名称" width="200" />
            <el-table-column property="pro_model" label="规格型号" />
            <el-table-column property="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.measure_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="入库单价" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
export default {
    setup() {
        const data = reactive({
            po_Name: "",//采购订单名称
            po_Code: "",//采购订单编号
            po_Vendor_Name: "",//供应商名称
            po_Endor_Code: "",//供应商编号
            contacts_Name: "",//联系人名称
            contacts_Phone: "",//联系人电话/联系方式
            po_Starttime: "",//订单签订日期
            po_Endtime: "",//订单交付日期
            po_Rep_Id: "",//销售订单负责人
            vendor_depd_id:"",//销售部门
            warehouse_Code: "",//仓库编号
            sale_total_qty: 0,//销售总数量
            cost_total_proce: 0,//成本总金额
            po_State: 0,//状态
            Remark: "",//备注
            del_Flag: '0',//删除状态
            create_By: localStorage.getItem('userLName'),//创建人
            create_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),//创建时间
        })
        const ruleFormRef = ref(null)//非空校验
        const rules = reactive({
            po_Name: [
                { required: true, message: "销售订单名称不能为空", trigger: ['blur', 'change'] },
            ], po_Vendor_Name: [
                { required: true, message: "客户名称不能为空", trigger: ['blur', 'change'] },
            ], po_Starttime: [
                { required: true, message: "订单签单日期不能为空", trigger: ['blur', 'change'] },
            ], po_Endtime: [
                { required: true, message: "订单交付日期不能为空", trigger: ['blur', 'change'] },
            ], po_Rep_Id: [
                { required: true, message: "采购负责人不能为空", trigger: ['blur', 'change'] },
            ], vendor_depd_id: [
                { required: true, message: "负责人部门不能为空", trigger: ['blur', 'change'] },
            ],
            po_Endor_Code: [
                { required: true, message: "供应商不能为空", trigger: ['blur', 'change'] },
            ]
        });
        const userOptions = ref([])//查询负责人信息
        const CKOptions = ref([])//仓库查询（需要修改）
        const customerOptons = ref([])//供应商信息
        const customer_name = ref("")//供应商查询条件
        const dialogTableVisible = ref(false)//点击添加采购明细按钮拟态框
        const productData = ref([])//产品库存
        const currentPage = ref(1)//第几页
        const pageSize = ref(5)//查几行
        const pageCount = ref(0)//总页数
        const productName = ref("")//查询库存名称条件
        const dict_code = ref("")//查询库存分类条件
        const measureOptios = ref([])//查询计量单位
        const multipleTableRef = ref(null); // 表格引用
        const selectedProducts = ref([]); // 存储选中的产品
        const selectedTable = ref(null);//表格引用
        const selectedRows = ref([]);//存储选中的数据
        const selectedData = ref([]); // 最终确认选择的数据
        const attributeOptios = ref([])
        const sale_total_qty = ref(0)//记录销售总数
        const sale_total_price = ref(0)//记录销售总额
        const cost_total_proce = ref(0)//记录产品成本总额
        const deptOptions = ref([]);//负责人所属部门
        const router = useRouter()

        onMounted(() => {
            //getUser()//查询负责人信息
            getCustomer()//查询供应商
            getMeasure()//查询计量单位
            getCK()//查询仓库信息
            getAttribute()
            getCustomer()
            productFill()
            productCount()
            getDept()
        })
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            // console.log("获取部门")
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                
                deptOptions.value = convertToTreeOptions(result.data)
                console.log(deptOptions)
                
            }).catch((err) => {
                console.info(err)
            });
        }

        watch(selectedData, (newVal) => {

            //每次计算时清空累加
            sale_total_qty.value = 0
            sale_total_price.value = 0
            cost_total_proce.value = 0
            newVal.forEach(row => {
                if (isNaN(Number(row.po_number))) {
                    ElMessage.warning('销售数量必须是数字');
                    row.po_number = 0;
                }

                // 验证销售单价
                if (isNaN(Number(row.pro_sale_price))) {
                    ElMessage.warning('采购单价必须是数字');
                    row.pro_sale_price = 0;
                }
                if(row.po_number > 999999){
                    ElMessage.warning('销售数量不能大于999999');
                    row.po_number = 0;
                }

                row.pro_total_cost = Number((row.po_number || 0) * (row.pro_cost_price || 0)).toFixed(2);

                sale_total_qty.value += Number(row.po_number)
                cost_total_proce.value += Number(row.pro_total_cost)
            });
        }, { deep: true });

        // function getUser() {
        //     axios.get("http://localhost:5181/api/User/GetUsers", {
        //         headers: {
        //             authorization: `Bearer ${localStorage.getItem('token')}`
        //         }
        //     }).then((result) => {
        //         userOptions.value = result.data
        //     }).catch((err) => {
        //         console.info(err)
        //     });
        // }
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: data.vendor_depd_id,
                    // name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getCK() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                CKOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getGYSname(){
            axios.get("http://localhost:5181/api/Values/Pinv_VendorWhere", {
                params: {
                    Vendor_name: data.po_Endor_Code
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                data.po_Vendor_Name = result.data
                console.log(data.po_Vendor_Name)
            }).catch((err) => {
                console.info(err)
            });
        }

        //防抖函数0.5秒后进行查询
        const getCustomerDebounced = debounce(getCustomer, 500);

        //查询供应商
        function getCustomer() {
            axios.get("http://localhost:5181/api/Values/Pinv_VendorWhere", {
                params: {
                    Vendor_name: customer_name.value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                customerOptons.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //把二维数据转换为结构数据
        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        //选择客户时赋值联系人名称和联系人电话
        function customerEndit() {
            const customer = customerOptons.value.find((cus) => cus.vendor_code == data.po_Endor_Code)
            // console.log(data.po_Endor_Code)
            // console.log(customer)
            data.contacts_Name = customer.contacts_name
            data.contacts_Name = customer.contacts_name
            data.contacts_Phone = customer.contacts_phone
            data.po_Vendor_Name = customer.vendor_name
        }

        function productAdd() {
            dialogTableVisible.value = true
        }

        //移除选中的table控件数据
        const productDel = () => {
            if (selectedRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            const selectedCodes = selectedRows.value.map(item => item.pro_code);
            selectedData.value = selectedData.value.filter(
                item => !selectedCodes.includes(item.pro_code)
            );

            if (selectedTable.value) {
                selectedTable.value.clearSelection();
            }

            selectedRows.value = [];
        };

        //分页查询产品库存信息
        function productFill() {
            axios.get("http://localhost:5181/api/Db_Product/Get_Products", {
                params: {
                    proName: productName.value,
                    typeCode: dict_code.value,
                    currentPage: currentPage.value,
                    pageSize: pageSize.value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                productData.value = result.data
                // console.log(productData.value)
            }).catch((err) => {
                console.info(err)
            });
        }

        //查询产品库存总数
        function productCount() {
            axios.get("http://localhost:5181/api/Db_Product/ProductCount", {
                params: {
                    proName: productName.value,
                    typeCode: dict_code.value,
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            productFill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            productFill();
        }

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                measureOptios.value = [{
                    dict_value: "0", dict_label: "请选择单位"
                }, ...result.data]
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //查询产品属性
        function getAttribute() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_pro_attribute"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                attributeOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据产品属性id返回产品属性名称
        function attributeValue(row) {
            if (!row) return "无";
            const parentDept = attributeOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //根据选择条件查询产品库存信息
        function productEedit() {
            // console.log(measureOptios.value)
            productFill()
            productCount()
        }

        //重置条件查询
        function productReaslt() {
            productName.value = ""
            dict_code.value = ""
            productFill()
            productCount()
        }

        // 表格选择变化时的处理函数
        const handleSelectionChange = (val) => {
            selectedProducts.value = val;
        };

        //点击确定存储选择的产品数据
        const handleConfirmSelection = () => {
            selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
                ...item,
                po_number: Number(0),//初始化销售数量为0
                pro_total_cost: Number(0).toFixed(2),//成本合计
                pro_sale_price: Number(item.pro_sale_price || 0).toFixed(2), // 格式化销售单价
                pro_cost_price: Number(item.pro_cost_price || 0).toFixed(2), // 格式化成本单价
            }))]//保存选择的产品数据
            dialogTableVisible.value = false
            multipleTableRef.value.clearSelection()//清空当前选择
        }

        //表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedRows.value = val;
        };

        //判断以添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedData.value.some(item => item.pro_code === row.pro_code);
        };

        //退出页面并删除当前页面的标签页
        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/Pinv/Po";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "销售订单",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        //点击保存按钮
        function handleAdd() {
            data.sale_total_qty = sale_total_qty;
            data.cost_total_proce = cost_total_proce;
            // getGYSname();
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    if (selectedData.value.length > 0) {
                        if (data.po_Code == "") {
                            obtainCode().then(() => {
                                    saleAdd()
                            }).catch((err) => {
                                console.info(err)
                            });
                        console.log("编号添加")
                        } else {
                            saleAdd()
                        console.log("添加")
                        }
                    } else {
                        ElMessage.warning('请选择要添加的产品数据');
                        return;
                    }
                }
            })
            console.log(data)
        }

        //获取编号
        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 11
                }
            }).then((result) => {
                data.po_Code = result.data
                console.log(data.po_Code)
            }).catch((err) => {
                console.info(err)
            });
        }

        //添加采购订单及其采购明细
        function saleAdd() {
            const pinv_detailsAddDto1 = selectedData.value.map(item => ({
                po_Code: data.po_Code,
                pro_name: item.pro_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.pro_model,
                unitmeas_id: item.measure_id,
                po_number: item.po_number,
                pro_sale_price: item.pro_sale_price,
                details_monovalent: item.pro_cost_price,
                details_storage:0,
                pro_total_cost: item.pro_total_cost,
                pb_operator: data.create_By,
            }))
            const pinvOrderDetailsDto = {
                pinv_Order_Dto: {
                    po_Vendor_Name: data.po_Vendor_Name,
                    po_Endor_Code: data.po_Endor_Code,
                    contacts_Name: data.contacts_Name,
                    contacts_Phone: data.contacts_Phone,
                    po_Name: data.po_Name,
                    po_Code: data.po_Code,
                    po_Starttime: data.po_Starttime,
                    po_Endtime: data.po_Endtime,
                    po_Rep_Id: data.po_Rep_Id,
                    po_depd_id:data.vendor_depd_id,
                    warehouse_Code: data.warehouse_Code,
                    po_quantity_purchased:data.sale_total_qty,
                    po_amount:data.cost_total_proce,
                    po_State:'0',
                    po_Audit:'0',
                    remark: data.Remark,
                    del_flag: data.del_Flag,
                    create_by: data.create_By,
                    create_time: data.create_Time
                },
                pinv_detailsAddDto: [...pinv_detailsAddDto1] // 创建详情数组的副本
            };
            // console.log(pinvOrderDetailsDto)
            axios.post("http://localhost:5181/api/Po/PostPoAdd", pinvOrderDetailsDto, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '销售订单添加成功！'
                    });
                    handleClose()
                }
            }).catch((err) => {
                console.info(err)
            });
        }

        return {
            data, userOptions, CKOptions, customerOptons, customer_name, getCustomerDebounced, customerEndit, dialogTableVisible,
            productAdd, productData, pageCount, pageSize, currentPage, productName, dict_code, handleSizeChange, handleCurrentChange, measureOptios,
            productEedit, productReaslt, selectedProducts, selectedData, multipleTableRef, handleSelectionChange, handleConfirmSelection, measureValue,
            attributeValue, attributeOptios, productDel, handleSelectedChange, sale_total_qty, sale_total_price, cost_total_proce, isDisabled, handleClose,
            handleAdd, ruleFormRef, rules,deptOptions,getDeptDebounced,getUser
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>